package utils;

import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


import utils.JNDIFactory;

public final class SystemStartup implements ServletContextListener {

	private static Logger jLog = Logger.getLogger(SystemStartup.class);

	public void contextInitialized(ServletContextEvent event) {
		//extracting the local directory path, needed for generating thumbnails
		event.getServletContext().setAttribute("localApplicationRootDirectory", DirectoryResolver.getAbsoluteBaseDirectoryPath());
		
		JNDIFactory jndiFactory = JNDIFactory.getInstance();

		try {
			// Initialize Logging
			String projectPath = jndiFactory.getEnvironmentAsString("projectPath");
			 
			if (projectPath.charAt(0) ==  '.' && projectPath.charAt(1) == '.' )
			{
				StringBuffer Buffer = new StringBuffer(projectPath);
				Buffer.delete(0, 2);
				
				StringBuffer relativePath = 
						new StringBuffer(SystemStartup.class.getClassLoader().getResource("").getPath());
				int index = relativePath.indexOf(".metadata");
				relativePath.delete(index-1, relativePath.length());
				String newProjectPath = relativePath.toString().substring(1).replace("%20", " ") + Buffer.toString();
				
				File logConfigFile = new File(newProjectPath
  										+ jndiFactory.getEnvironmentAsString("configPath")
  										+ "/log4j.properties");

				if (!logConfigFile.exists()) {
					System.out.println("ERROR: Logging configuration file not found: " 
									+ newProjectPath
									+ jndiFactory.getEnvironmentAsString("configPath")
									+ "/log4j.properties");
				} else {
					String logpath = logConfigFile.getPath();
					PropertyConfigurator.configure(logpath);
				}
				jLog.info("ContextInitialized");
			}
			else
			{
				File logConfigFile = new File(jndiFactory.getEnvironmentAsString("projectPath")
					  						+ jndiFactory.getEnvironmentAsString("configPath")
					  						+ "/log4j.properties");

				if (!logConfigFile.exists()) {
					System.out.println("ERROR: Logging configuration file not found: " 
									+ jndiFactory.getEnvironmentAsString("projectPath")
								  	+ jndiFactory.getEnvironmentAsString("configPath")
								  	+ "/log4j.properties");
				} else {
					String logpath = logConfigFile.getPath();
					PropertyConfigurator.configure(logpath);
				}
				jLog.info("ContextInitialized");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		jLog.info("ContextDestroyed");
	}

}
